package com.study.io.bio.demo.output;

import com.study.io.bio.demo.input.PipedInputStreamDemo;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * 管道输出流
 * 主要是为运行在同一个JVM中的两个线程提供通信能力
 *
 * @author wuxj
 */
public class PipedOutputStreamDemo implements Runnable {
    // 管道输出流
    private PipedOutputStream output;

    public PipedOutputStreamDemo(PipedOutputStream output) {
        this.output = output;
    }

    @Override
    public void run() {
        String str = "hello, piped!";
        try {
            // 向管道输入流(PipedInputStream)的缓冲区写入数据
            output.write(str.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭管道输出流
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        try {
            /** 管道输出流和输入流定义 */
            PipedOutputStream output = new PipedOutputStream();
            PipedInputStream input = new PipedInputStream();

            /** 写线程和读线程创建 */
            PipedOutputStreamDemo pipedOutputStreamDemo = new PipedOutputStreamDemo(output);
            PipedInputStreamDemo pipedInputStreamDemo = new PipedInputStreamDemo(input);

            Thread tWrite = new Thread(pipedOutputStreamDemo);
            Thread tRead = new Thread(pipedInputStreamDemo);

            /** 管道输入流和输出流通过connect方法建立关联关系 */
            output.connect(input);

            /** 通过start启动线程 */
            tWrite.start();
            tRead.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
